#!/bin/bash
DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
ROOT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )"/.. && pwd )
source $DIR/environment

LOG_FILE="$DIR/setup.log"

yell() { echo "$0: $*" >&2; }
die() { yell "$*"; exit 111; }
try() {
    # Append command to log file
    echo -e "\n>>> $*\n" >> $LOG_FILE
    # Execute command and redirect output to logfile. Exit in case or error.
    "$@" >> $LOG_FILE 2>&1 || die "cannot $*. Check $LOG_FILE for details.";
}

$DIR/check
if [ $? -eq 0 ]; then
    DOCKER_IP=localhost

    echo "Deleting docker containers..."
    $DIR/down

    if [ ! -f $ROOT_DIR/polyaxon/polyaxon/env_vars/local.json ]; then
        cp $ROOT_DIR/polyaxon/polyaxon/env_vars/local_template.json $ROOT_DIR/polyaxon/polyaxon/env_vars/local.json;
    fi

    # echo "Collecting static assets..."
    $DIR/manage collectstatic --noinput

    rm -f $LOG_FILE || true

    echo "Initialising database schema..."
    $DIR/manage migrate

    $DIR/manage loaddata polyaxon/fixtures/db.json
fi
